package com.schema2uml;

import java.io.File;
import java.util.TreeMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLHelper {
			
	public static TreeMap<String, String> getTypeMappings(String file) throws Exception {
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder  = factory.newDocumentBuilder();
        Document document = builder.parse( new File( file ) );
        TreeMap<String, String> typeMappings = new TreeMap<String, String>();
        NodeList list = document.getElementsByTagName( "type" );
        for (int i=0; i<list.getLength(); i++){
	      	Node node = list.item(i); 
	      	NodeList content = node.getChildNodes();
	      	String dbType = null;
	      	String modelType = null;
	      	for (int j=0; j<content.getLength(); j++) {
	      		Node n = content.item(j);
	      		if (n.getNodeName().equalsIgnoreCase("db-type")){
	      			dbType = n.getTextContent();
	      		}
	      		if (n.getNodeName().equalsIgnoreCase("model-type")){
	      			modelType = n.getTextContent();
	      		}
	      	}
	      	if (dbType != null && modelType != null){
	      		typeMappings.put(dbType, modelType);
	      	}
        }
        return typeMappings;
    }

	public static TreeMap<String, String> getClassNameReplacementRules(String file) throws Exception {
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder  = factory.newDocumentBuilder();
        Document document = builder.parse( new File( file ) );
        TreeMap<String, String> rules = new TreeMap<String, String>();
        NodeList list = document.getElementsByTagName( "replacement" );
        for (int i=0; i<list.getLength(); i++){
	      	Node node = list.item(i); 
	      	NodeList content = node.getChildNodes();
	      	String replaceAll = null;
	      	String with = null;
	      	for (int j=0; j<content.getLength(); j++) {
	      		Node n = content.item(j);
	      		if (n.getNodeName().equalsIgnoreCase("replace-all")){
	      			replaceAll = n.getTextContent();
	      		}
	      		if (n.getNodeName().equalsIgnoreCase("with")){
	      			with = n.getTextContent();
	      		}
	      	}
	      	if (replaceAll != null && with != null){
	      		rules.put(replaceAll, with);
	      	}
        }
        return rules;
    }
	
}
